package com.fund.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fund.api.entity.TradeOrder;
import com.fund.client.constants.BankCardConstants;
import com.fund.client.mapper.BankCardMapper;
import com.fund.client.pojo.entity.BankCard;
import com.fund.client.pojo.entity.BankCardFlow;
import com.fund.client.pojo.entity.Client;
import com.fund.client.service.BankCardFlowService;
import com.fund.client.service.BankCardService;
import com.fund.client.service.ClientService;
import com.fund.common.enums.FlowChangeReason;
import com.fund.common.enums.FlowChangeType;
import com.fund.common.pojo.Result;
import com.fund.common.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BankCardServiceImpl extends ServiceImpl<BankCardMapper, BankCard> implements BankCardService {


    @Autowired
    ClientService clientService;

    //银行卡必须是16或19位数字且不以0开头
    private static final String BANK_CARD_REGEX = "^(?!0)\\d{16}|\\d{19}$";

    @Autowired
    BankCardFlowService bankCardFlowService;

    /**
     * 新增银行卡
     * @param bankCard
     * @return
     */
    @Override
    public Result<Boolean> addBankCard(BankCard bankCard) {
        //校验银行卡号
        if(bankCard.getCardNumber() == null || bankCard.getCardNumber().trim().isEmpty()
                || ! bankCard.getCardNumber().matches(BANK_CARD_REGEX)) {
            return Result.fail("银行卡号格式错误（需16或19位数字且不以0开头）");
        }
        //校验客户是否在系统中
        if(bankCard.getClientId() == null){
            return Result.fail("该客户不存在");
        }
        Client client = clientService.getById(bankCard.getClientId());
        if(client == null){
            return Result.fail("该客户不存在");
        }

        //设置银行卡默认初始值
        bankCard.setBalance(BankCardConstants.DEFAULT_BALANCE);

        //保存并返回
        return Result.success(save(bankCard));
    }

    /**
     * 根据客户id查询银行卡
     * @param clientId
     * @return
     */
    @Override
    public Result<List<BankCard>> getByClientId(Long clientId) {
        //判断是否为空
        if(clientId == null ){
            return Result.fail("客户id不能为空");
        }
        //查询银行卡
        List<BankCard> bankCards = lambdaQuery().eq(BankCard::getClientId, clientId).list();
        //返回
        return Result.success(bankCards);
    }

    /**
     * 根据订单更新银行卡余额
     * @param tradeOrderList
     * @return
     */
    // TODO 效率很低，每次都需要操作很多次数据库
    // TODO 可以添加分布式锁处理并发问题
    @Override
    public Result<Boolean> updateBalanceByOrders(List<TradeOrder> tradeOrderList) {
        for (TradeOrder order : tradeOrderList) {
            BankCard bankCard = getById(order.getCardId());
            update(new LambdaUpdateWrapper<BankCard>()
                    .eq(BankCard::getId, order.getCardId())
                    .setSql("amount = amount - " + order.getAmount().toString()));
            BankCardFlow bankCardFlow = new BankCardFlow();
            bankCardFlow.setCardId(bankCard.getId());
            bankCardFlow.setNewBalance(bankCard.getBalance().add(order.getAmount()));
            bankCardFlow.setReason(FlowChangeReason.REDEMPTION);
            bankCardFlow.setFundId(order.getFundId());
            bankCardFlow.setChangeTime(LocalDateTime.now());
            bankCardFlow.setChangeValue(order.getAmount());
            bankCardFlow.setOperatorId(UserContext.getUser());
            bankCardFlow.setTradeTime(order.getCreateTime());
            bankCardFlow.setTransactionType(FlowChangeType.INCOME);
            bankCardFlowService.save(bankCardFlow);
        }
        return Result.success();
    }
}
